package com.mz.mattress.client.timer.impl;

import com.mz.mattress.api.entity.OrderUseTimes;
import com.mz.mattress.api.util.DateUtil;
import com.mz.mattress.client.common.Holder;
import com.mz.mattress.client.mapper.OrderUseTimesMapper;
import com.mz.mattress.client.service.OrderUseTimesService;
import com.mz.mattress.client.timer.TimerTask;
import io.netty.util.Timeout;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class GenOrderTask implements TimerTask {

    @Autowired
    private OrderUseTimesMapper orderUseTimesMapper;

    @Autowired
    private OrderUseTimesService orderUseTimesService;

    @Override
    public boolean canDo() {
        return true;
    }

    @Override
    public void run() {

        String endTime = DateUtil.plusMin(6);
        List<OrderUseTimes> list = orderUseTimesMapper.selectOvertime(endTime);

        for (OrderUseTimes times : list) {

            OrderUseTimes update = new OrderUseTimes();
            update.setId(times.getId());
            update.setPlan(1);
            orderUseTimesMapper.updateById(update);

            long second = DateUtil.getToNowSecond(times.getEndTime());
            if (second < 0) {
                second = 0;
            }

            log.info("device_stop_task_add_task_id={},second={}", times.getId(), second);

            Holder.DELAY_TIMER.newTimeout(new io.netty.util.TimerTask() {
                @Override
                public void run(Timeout timeout) throws Exception {
                    orderUseTimesService.stop(times.getId());
                }
            }, second, TimeUnit.SECONDS);
        }

    }

    public static void main(String[] args) {


        String ss = DateUtil.plusMin(-5);

        System.out.println(ss);

    }

}
